<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-04-05
 * Time: 21:59
 */

namespace App\Services\Impl;


use App\Common\Constant\Params;
use App\Events\MasterOrderRefund;
use App\Models\Order;
use App\Models\OrderOffer;
use App\Models\OrderRefund;
use App\Models\OrderStatus;
use App\Services\IRefundService;
use DB;
use Illuminate\Support\Collection;
use Log;

class RefundServiceImpl implements IRefundService
{

    public function listRefund($master_id)
    {
        $orderIds = OrderOffer::where(["master_id"=>$master_id,"status"=>Params::OFFER_STATUS_EMPLOYED])->select('order_id')->get()->pluck('order_id');
        if ($orderIds->isEmpty()){
            return Collection::make([]);
        }
        $orderIds = OrderRefund::whereIn("order_id",$orderIds)->get()->pluck('order_id');
        if ($orderIds->isEmpty()){
            return Collection::make([]);
        }
        return Order::whereIn("id",$orderIds)->with('status','merchant','refunds')->get()->sortByDesc(function ($item, $key) {
            return $item->refund->add_time;
        });
    }

    public function agreeRefund($refund_id)
    {
        $refund = OrderRefund::find($refund_id);
        if (!$refund){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'miss refund'));
            return false;
        }

        return $refund->update([
            'refund_result_time'=>time(),
            'refund_result_type'=>Params::ORDER_REFUND_RESULT_AGREE,
        ]) && event(new MasterOrderRefund($refund_id));
    }

    public function disagreeRefund($refund_id, $refuse_reason = null)
    {
        $refund = OrderRefund::find($refund_id);
        if (!$refund){
            Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'miss refund'));
            return false;
        }

        return $refund->update([
                'refund_result_time'=>time(),
                'refund_result_type'=>Params::ORDER_REFUND_RESULT_DISAGREE,
                'refund_refuse_reason'=>$refuse_reason
            ])
            && OrderStatus::where('order_id',$refund->order_id)->take(1)->update([
                'refund_status'=>Params::ORDER_REFUND_REFUSE,
            ])
            && event(new MasterOrderRefund($refund_id));
    }

}